<?php
namespace common\formatter;

use common\lib\formatter\Formatter;
use common\lib\formatter\Type;

/**
 * 用户数据结构格式化 -- demo
 */
class UserFormatter extends Formatter
{

    protected static $fields = [
        'id' => Type::INT,
        'screen_name' => Type::STRING, //昵称
        'avatar' => Type::STRING, //头像
        'gender' => GenderType::class, //性别
        'created_at' => Type::INT, //注册时间
        'amount' => Type::FLOAT, //账户余额
        'is_vip' => Type::BOOL, //是否VIP
        'fans_count' => [
            'type' => Type::INT,
            'optional' => true, //传入字段中存在此字段，才会返回此数据项
        ],
        'tags' => [ //数据结构 用户有多个兴趣标签
            'type' => Type::STRING,
            'repeated' => true,
        ],
    ];

    protected static function item($key, $item, $type, &$info = null)
    {
        if ($key == 'amount') {
            $item = round($info['total_amount'] / 100, 2);
        } else {
            $item = parent::item($key, $item, $type, $info);
        }
        return $item;
    }

}